package com.followmeandroid;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.followmeandroid.enums.ResultCode;
import com.followmeandroid.enums.ServiceUrl;
import com.followmeandroid.messages.AddFriendRequest;
import com.followmeandroid.messages.FindFriendRequest;
import com.followmeandroid.messages.FindFriendResponse;
import com.followmeandroid.models.CurrentMember;
import com.followmeandroid.models.Friend;
import com.followmeandroid.util.FollowMeSharedPreferences;
import com.followmeandroid.util.JSONHttpClient;

import static com.followmeandroid.R.layout.activity_friendsearch;
/**
 * <p>Title: FriendSearchActivity</p>
 * <p>Description: This activity controls the content and
 * functionality of the Friends Search screen.</p>
 * @team Adam Drews
 * @email adam.drews@my.uwrf.edu
 * @team Tyler Johnson
 * @email tyler.johnson@my.uwrf.edu
 * @team Nicholas Thorp
 * @email nicholas.thorp@my.uwrf.edu
 * @date 11/17/2014
 */
public class FriendSearchActivity extends ListActivity {

    private EditText etEditFriendName;
    private Button bSearchFriend;
    private Context thisContext;
    private ListAdapter friendListAdapter;
    private FindFriendResponse searchResults;

    /**
     * Creates the layout for the current view. It is passed a
     * bundle of data from the previous activity.
     * @param bundle        The information passed from the main activity.
     */
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(activity_friendsearch);

        thisContext = this;

        etEditFriendName = (EditText) findViewById(R.id.editFriendText);
        bSearchFriend = (Button) findViewById(R.id.searchFriendBtn);

        etEditFriendName.setOnClickListener(new View.OnClickListener() {
            /**
             * Clears the text field when the user clicks into it.
             * @param v     The current view.
             */
            @Override
            public void onClick(View v) {
                etEditFriendName.setText("");
            }
        });
        bSearchFriend.setOnClickListener(new View.OnClickListener() {
            /**
             * Searches for the friend name in the text field
             * by calling the searchForFriend method.
             * @param v     The current view.
             */
            @Override
            public void onClick(View v) {
            searchForFriend(etEditFriendName.getText().toString());
            }
        });

        Intent intent = getIntent();
        bundle = intent.getExtras();
        if (bundle != null) {
            searchForFriend(bundle.get("search").toString());
        }

    }

    /**
     * Controls the action taken when a friend in the list is clicked.
     * @param l             The list of friends.
     * @param v             The current view.
     * @param position      The position in the list of the clicked friend.
     * @param id            Id number
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Friend friend = (Friend) getListAdapter().getItem(position);
        Toast.makeText(this, friend.getUserName() + " selected", Toast.LENGTH_LONG).show();
        addFriend(friend);
    }

    /**
     * Adds the friend in the list that the user clicked on.
     * @param friend        The friend to be added.
     */
    private void addFriend(final Friend friend) {
        AddFriendRequest addfriend = new AddFriendRequest(friend.getFriendID());

        new AsyncTask<AddFriendRequest, JSONHttpClient, Integer>() {
            /**
             * The operation to be performed by the thread in the background.
             * @param params        A delete friend request.
             * @return result       The result from the request.
             */
            @Override
            protected Integer doInBackground(AddFriendRequest... params) {
                Integer result = 0;

                try {
                    // Call post, add friends.
                    result = JSONHttpClient.PostObject(ServiceUrl.POST_FRIEND.toString(), params[0], AddFriendRequest.class);

                } catch (Exception e) {
                    Log.d("AsyncAddFriend", e.getMessage());
                }
                return result;
            }

            /**
             * Displays a please wait pop up before the thread executes.
             */
            @Override
            protected void onPreExecute() {

                super.onPreExecute();
                Toast.makeText(thisContext, "Please Wait...", Toast.LENGTH_SHORT).show();
            }

            /**
             * Displays the result from trying to add the friend. This result is determined
             * be a result code received by the server.
             * @param result        The failure or success of the action.
             */
            @Override
            protected void onPostExecute(Integer result) {
                // TODO Auto-generated method stub
                //result is http result code, 200 = OK
                if (ResultCode.get(result) == ResultCode.OK) {
                    CurrentMember.getMember().addFriend(friend);
                    FollowMeSharedPreferences.saveMember();
                } else {
                    //make them try again!
                    Toast.makeText(thisContext, "Friend not found, or you are friends already!", Toast.LENGTH_LONG).show();
                }
                searchResults.getFriends().remove(friend);
                friendListAdapter = new ArrayAdapter<Friend>(thisContext, android.R.layout.simple_list_item_1, searchResults.getFriends());
                setListAdapter(friendListAdapter);
            }
        }.execute(addfriend);
    }

    /**
     * Sends a request to the server to retrieve a list of friends
     * that match with the given search parameters.
     * @param search        The content to be searched for.
     */
    private void searchForFriend(String search){
        FindFriendRequest find = new FindFriendRequest(search);

        new AsyncTask<FindFriendRequest, JSONHttpClient, FindFriendResponse> (){
            /**
             * The operation to be performed by the thread in the background.
             * @param params        A find friend request.
             * @return result       The result from the request.
             */
            @Override
            protected FindFriendResponse doInBackground(FindFriendRequest... params) {
                //create a registration request

                FindFriendResponse result = null;

                try {
                    // Call getter, find friends.
                    result = JSONHttpClient.Get(ServiceUrl.FIND_FRIEND.toString(), params[0].toKeyValuePairs(), FindFriendResponse.class);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    Log.d("AsyncLogin", e.getMessage());
                }
                return result;
            }

            /**
             * Displays a please wait pop up before the thread executes.
             */
            @Override
            protected void onPreExecute() {

                super.onPreExecute();
                Toast.makeText(thisContext, "Please Wait...", Toast.LENGTH_SHORT).show();
            }

            /**
             * Displays the result from trying to find the friend. This result is determined
             * be a result code received by the server.
             * @param result        The failure or success of the action.
             */
            @Override
            protected void onPostExecute(FindFriendResponse result) {
                // TODO Auto-generated method stub
                if (result != null && result.getFriends() != null && !result.getFriends().isEmpty()) {
                    searchResults = result;
                    friendListAdapter = new ArrayAdapter<Friend>(thisContext, android.R.layout.simple_list_item_1, result.getFriends());
                    setListAdapter(friendListAdapter);
                } else {
                    //make them try again!
                    Toast.makeText(thisContext, "Nothing found", Toast.LENGTH_LONG).show();
                    friendListAdapter = new ArrayAdapter<Friend>(thisContext, android.R.layout.simple_list_item_1);
                    setListAdapter(friendListAdapter);
                }
            }
        }.execute(find);
    }
}
